package com.fs.sys.service;

import cn.hutool.core.codec.Base64Encoder;
import com.fs.common.base.service.CacheService;
import com.fs.common.exception.AppException;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * 图形验证码服务
 *
 * @author LiuQi 2025/6/19-10:22
 * @version V1.0
 **/
@Service
@Slf4j
public class KaptchaService {
    @Autowired
    private DefaultKaptcha kaptcha;

    @Autowired
    private CacheService cacheService;

    /**
     * 图形验证码校验
     * @param key key
     * @param code 用户输入的验证码
     */
    public void checkCode(String key, String code) {
        String exist = cacheService.getAndDelete("imageCode:" + key);
        if (!StringUtils.equalsIgnoreCase(code, exist)) {
            throw AppException.of("图形验证码无效");
        }
    }

    /**
     * 图形验证码生成失败
     * @param key key
     * @return 图形内容
     */
    public String generate(String key) {
        String text = kaptcha.createText();
        cacheService.cache("imageCode:" + key, text);
        BufferedImage image = kaptcha.createImage(text);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", outputStream);
        } catch (IOException e) {
            log.error("生成图形验证码失败", e);
            throw AppException.of("生成图形验证码失败");
        }

        String str = "data:image/jpeg;base64,";
        return str + Base64Encoder.encode(outputStream.toByteArray()).replace("\n", "").replace("\r", "");
    }
}
